<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS ViewController生命周期"><meta name="keywords" content="iOS,动画"><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS ViewController生命周期 | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-4"><a class="toc-link" href="#ViewController%E7%9A%84%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F"><span class="toc-number">1.</span> <span class="toc-text">ViewController的生命周期</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#viewWillLayoutSubviews%E8%B0%83%E7%94%A8%E6%83%85%E5%86%B5%E5%88%86%E6%9E%90"><span class="toc-number">1.0.1.</span> <span class="toc-text">viewWillLayoutSubviews调用情况分析</span></a></li></ol></li></ol></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS ViewController生命周期</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2016-04-07</time></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><h4 id="ViewController的生命周期"><a href="#ViewController的生命周期" class="headerlink" title="ViewController的生命周期"></a>ViewController的生命周期</h4><figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 类的加载方法</span></span><br><span class="line"><span class="comment">// 是加载类的时候调用。也就是说，iOS应用启动时会加载所有的类，所有的类就都会调一次这个方法。</span></span><br><span class="line"><span class="comment">// 一个类的 `+load` 方法是在其父类的 `+load` 方法调用后再调用</span></span><br><span class="line"><span class="comment">// 一个`Category`的 `+load` 方法在被其扩展的类调完自有 `+load` 方法后才会调用</span></span><br><span class="line">+ (<span class="type">void</span>)load;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 类的初始化方法</span></span><br><span class="line"><span class="comment">// 当某个类调用 alloc 方法时，将为实例在堆上分配空间时，调用一次initialize方法</span></span><br><span class="line"><span class="comment">// 而且该方法只调用一次，也就是说再次 alloc 操作的时候，不会再调用 initialize 这个方法了。</span></span><br><span class="line">+ (<span class="keyword">instancetype</span>)initialize;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>更多：<a target="_blank" rel="noopener" href="//http://blog.leichunfeng.com/blog/2015/05/02/objectivec-plus-load-vs-plus-initialize/">objectivec +load vs +initialize</a></p>
<p><strong>视图控制器push显示：</strong>(执行顺序依次从上往下)</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">// 对象的初始化方法</span></span><br><span class="line">- (<span class="keyword">instancetype</span>)init;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 加载视图</span></span><br><span class="line">- (<span class="type">void</span>)loadView;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图加载完毕时调用</span></span><br><span class="line">- (<span class="type">void</span>)viewDidLoad;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图将要显示的时候调用</span></span><br><span class="line">- (<span class="type">void</span>)viewWillAppear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图中的子视图将要布局时调用</span></span><br><span class="line">- (<span class="type">void</span>)viewWillLayoutSubviews;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图中的子视图布局完毕时调用</span></span><br><span class="line">- (<span class="type">void</span>)viewDidLayoutSubviews;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图显示完毕的时候调用</span></span><br><span class="line">- (<span class="type">void</span>)viewDidAppear:(<span class="type">BOOL</span>)animated;</span><br></pre></td></tr></table></figure>



<p><strong>视图控制器pop消失</strong>：</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 视图将要消失</span></span><br><span class="line">-(<span class="type">void</span>)viewWillDisappear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 视图已经消失</span></span><br><span class="line">-(<span class="type">void</span>)viewDidDisappear:(<span class="type">BOOL</span>)animated;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 对象被释放前调用</span></span><br><span class="line">-(<span class="type">void</span>)dealloc;</span><br></pre></td></tr></table></figure>



<p><strong>总结：</strong></p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alloc -&gt; initWithNibName -&gt; loadView -&gt; viewDidLoad -&gt; viewWillAppear -&gt; viewDidAppear -&gt; viewWillDisappear -&gt; viewDidDisappear -&gt; dealloc</span><br></pre></td></tr></table></figure>



<p><strong>注意点：</strong></p>
<ul>
<li><p>1、<code>viewWillAppear</code></p>
<blockquote>
<p>其实在viewWillAppear这里改变UI元素不是很可靠，Autolayout发生在viewWillAppear之后，严格来说这里通常不做视图位置的修改，而用来更新Form数据。改变位置可以放在viewWilllayoutSubview或者didLayoutSubview里，而且在viewDidLayoutSubview确定UI位置关系之后设置autoLayout比较稳妥。另外，viewWillAppear在每次页面即将显示都会调用，viewWillLayoutSubviews虽然在lifeCycle里调用顺序在viewWillAppear之后，但是只有在页面元素需要调整时才会调用，避免了Constraints的重复添加。</p>
</blockquote>
</li>
</ul>
<p>引用：<a target="_blank" rel="noopener" href="http://casatwy.com/iosying-yong-jia-gou-tan-viewceng-de-zu-zhi-he-diao-yong-fang-an.html">iOS应用架构谈 view层的组织和调用方案</a></p>
<ul>
<li>2、<code>initWithNibName:bundle:</code></li>
</ul>
<blockquote>
<p>1）在这个函数中应该只有相关数据的初始化，而且这些数据都是比较关键的数据，不要出现创建view的代码，也不要调<code>self.view</code>（<code>viewDidLoad</code>中view才加载到内存中），否则会导致ViewController创建view;View的创建留给后面的方法。</p>
<p>2）如果你是用 xib 创建 view 并初始化 ViewController，意味着你要使用 <code>initWithNibName:bundle:</code> 方法</p>
</blockquote>
<ul>
<li>3.<code>loadView</code></li>
</ul>
<blockquote>
<p>1）添加subView应该在viewDidLoad里去做，此时不要实现自己的loadView</p>
<p>2）如果重写，一定要首先调用[super loadView],否则会循环调用loadView方法。调用[super loadView]一系列操作也会影响CPU性能，所以可以直接手动创建self.view &#x3D; [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];<br>原因：loadView,其实是lazy load的,就是懒加载，每次访问UIViewController的view(比如controller.view、self.view)而且view为nil，loadView方法就会被调用。<br>[super loadView] 方法会加载xib文件来创建UIViewController的view,如果没有xib则创建一个空白的View<code>self.view = [[UIView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame]</code>;<br>如果你重写了这个方法,那么系统就会调用loadView,调用完后,再自动调用ViewDidLoad函数.这时就有可能造成死循环,所以非常不建议重写loadView方法。<br>当然在视图内存紧张情况，可适当考虑此方法，但经常出现内存警告时更应当从内存优化入手<br>3) 如果你是用 xib 创建 view 并初始化 ViewController，意味着你要使用 initWithNibName:bundle: 方法，则不要覆盖 loadView 方法。</p>
</blockquote>
<p><code>viewDidLoad</code></p>
<p>由于view已经加载到内存中，所以<code>self.view !=nil</code>，我们可以随心所欲的添加<code>addSubview</code>,或者填充数据;</p>
<p><code>-(void)viewWillAppear:(BOOL)animated</code>与<code>-(void)viewDidAppear:(BOOL)animated</code></p>
<p>适合KVO的添加与移除等操作,切换前后台不会调用viewWillAppear.</p>
<h6 id="viewWillLayoutSubviews调用情况分析"><a href="#viewWillLayoutSubviews调用情况分析" class="headerlink" title="viewWillLayoutSubviews调用情况分析"></a><code>viewWillLayoutSubviews</code>调用情况分析</h6><ul>
<li>init初始化不会触发layoutSubviews</li>
<li>addSubview会触发layoutSubviews</li>
<li>设置view的Frame会触发layoutSubviews，当然前提是frame的值设置前后发生了变化</li>
<li>滚动一个UIScrollView会触发layoutSubviews</li>
<li>旋转Screen会触发父UIView上的layoutSubviews事件</li>
<li>改变一个UIView大小的时候也会触发父UIView上的layoutSubviews事件</li>
</ul>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2016/04/07/iOS ViewController生命周期/">http://huluo666.gitee.io/2016/04/07/iOS ViewController生命周期/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/iOS-%E5%8A%A8%E7%94%BB/">iOS,动画</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2016/04/07/Mac%20%E5%BF%AB%E6%8D%B7%E9%94%AE/"><i class="fa fa-chevron-left">  </i><span>Mac 快捷键</span></a></div><div class="next-post pull-right"><a href="/2016/04/06/iOS%E7%BB%98%E5%9B%BE%E4%B8%8E%E5%8A%A8%E7%94%BB%E7%B3%BB%E5%88%97%20Core%20Graphics%E4%B8%8EQuartz%202D%EF%BC%88%E4%B8%80%EF%BC%89/"><span>iOS绘图与动画系列 Core Graphics与Quartz 2D（一）</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>